/* 递归/非递归方式遍历文件夹.
  需自行实现回调函数. */
int wavcam_direntcb(const char* dir, 
        int recursive, 
        int depth,
        int (*cb)(struct dirent* d, int depth, void* arg), 
        void* arg)
{
    int ret = 0;

    DIR* dirp;
    struct dirent entry;
    struct dirent* result = NULL;
    int retdir;

    dirp = opendir(dir);
    if(NULL != dirp) {
        while(1) {
            result = NULL;
            retdir = readdir_r(dirp, &entry, &result);
            if(0 != retdir) {
                ulogerr("%s error : readdir_r at %s.\n", __FUNCTION__, dir);
                ret = -1;
                break;
            }

            if(0 == retdir && NULL == result) {
                ulogdbg("%s finished at %s.\n", __FUNCTION__, dir);
                break;
            }

            if(0 == strcmp(entry.d_name, ".") 
                    || 0 == strcmp(entry.d_name, "..")) {
                continue;
            }

            retdir = cb(&entry, depth, arg);
            if(0 == retdir && recursive) {
                #define LEN_DPATH   (10*1024)
                char path[LEN_DPATH];
                if(4 == entry.d_type) {
                    snprintf(path, LEN_DPATH, "%s/%s", dir, entry.d_name);
                    wavcam_direntcb(path, 1, depth+1, cb, arg);
                }
            }
        }

        closedir(dirp);
        dirp = NULL;
    }
    else {
        ulogerr("%s error : opendir at %s.\n", __FUNCTION__, dir);
        ret = -1;
    }

    return ret;
}
